var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var reload = true;
var page = 1;
var hasMore = true;
var loadingMore = false;

var SDKVersion = '';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    util: util,
    imgDomain: app.globalData.imgDomain,

    classlysData: '',

    ghsData: [],
    hasData: true,

    uid: 0,
    token: '',
    openid: '',
    canEdit: 0,

    bottom_nav_data: [],
    isIphone_x: false,
    nav_bgColor: '#ffffff',

    shouqian_phone: '',
    colorSet: '',
    wz_item_img_w_1: 300,
    showRoomTypes:true,

    btype:1,
    btypename:'',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
      brtime: options.brtime,
      btype:options.btype,
    });

    wx.showLoading({
      title: tc == 1 ? '加載中' : '加载中',
      mask: 'true'
    });

    if (options.btype == 1) {
      var titlename = '时租房';
      that.setData({
        btype: options.btype,
        btypename:'时租'
      });
    } if (options.btype == 2) {
      var titlename = '日租房';
      that.setData({
        btype: options.btype,
        btypename: '日租'
      });
    } if (options.btype == 3) {
      var titlename = '月租房';
      that.setData({
        btype: options.btype,
        btypename: '月租'
      });
    }
    console.log("type1111111111111111111", that.data.btype)
    console.log("type2222222222222222222", that.data.btypename)
    wx.setNavigationBarTitle({
      title: titlename,
    }); 

    page = 1;
    hasMore = true;
    loadingMore = false;

    var that = this;

    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color,
      })
      that.resetNavColor();
    });

    //初始化底部导航
    var b_nav_data = app.getBottomNavData('ghs_list/ghs_list', function (data) {
      that.setData({
        bottom_nav_data: data,
        nav_bgColor: data[0].bgcolor,
      });
    });

    wx.getSystemInfo({
      success: function (res) {
        SDKVersion = res.SDKVersion;
        var isIphone_x = (res.model.indexOf('iPhone X') >= 0);
        that.setData({
          tc: app.get_tc(),
          isIphone_x: isIphone_x,
          wz_item_img_w_1: res.windowWidth - 25
        });
      }
    })

    reload = true;
    //当前登录用户信息
    app.LoginUserInfo(function (res) {
      var authFail = res == -1;//用户拒绝授权
      if (!authFail) {
        //更新数据
        that.setData({
          userInfo:res,
          uid: res.uid,
          token: res.token,
          openid: res.wxsmall_openid
        });
      }

    });
    //获取关于等信息
    app.getAllAbout('shouqian', function (res) {
      that.setData({
        shouqian_phone: res
      })
    });
    //读取文字分类
    // this.loadGHS(1);
    // this.loadAttributeGroups();
  },

  

  loadMore: function (e) {
    if (hasMore && !loadingMore) {
      loadingMore = true;
      page++;
      this.loadGHS(page);
    } else {
      console.log("没有更多了");
    }
  },

  // 读取动态 （近况）
  loadGHS: function (cpage) {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getghs",
      orgid: util.orgid,
      page: cpage,
      num: 10
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("供货商数据：", result);
        if (!result.msg) {
          // result.forEach(function (m, i) {
          //   if (m.photos) {
          //     result[i].photosData = m.photos.split(",");
          //   }
          //   result[i].message = app.parseHTMLText(m.message);
          // });

          if (cpage <= 1) {
            that.setData({
              ghsData: result
            });

          } else {

            that.setData({
              ghsData: that.data.ghsData.concat(result)
            });

          }

          var ghsData = that.data.ghsData;
          console.log("that.data.userInfo", that.data.userInfo)
          if (that.data.userInfo) {
            //计算直线距离
            ghsData.forEach(function (m, i){
              var distanStr = '';
                var distan = app.getDistance(that.data.userInfo.lat, that.data.userInfo.lon, m.lat, m.lon);
              if (distan > 1000) {
                distanStr = (distan / 1000).toFixed(2) + 'km';
              } else {
                distanStr = distan.toFixed(0) + 'm';
              }
              m.distanse = distanStr;
              m.distansenum = distan;
              // m.ghsscore = (m.scorecoin / m.scorenum).toFixed(1);
            });
          }
          // 评分
          ghsData.forEach(function (m, i) {
            m.ghsscore = (m.scorecoin / m.scorenum).toFixed(1);
          });
          // 去除家家烘焙店
          for (var i = 0; i < ghsData.length; i++) {
            if (ghsData[i].gcataid == 0) {
              ghsData.splice(i,1);
              i--
            }
          }
          that.setData({
            ghsData: ghsData
          });
          that.getGoodsClassly();
        } else {
          if (cpage <= 1) {

            that.setData({
              ghsData: []
            });

          }

          hasMore = false;


        }
        loadingMore = false;

        if (that.data.ghsData.length <= 0) {
          that.setData({
            hasData: false
          })
        } else {
          that.setData({
            hasData: true
          })
        }
        wx.hideLoading();
      }
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.loadGHS(1);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  //页面分享
  onShareAppMessage: function () {
    var that = this;
    var inviteuid = that.data.loginuid ? that.data.loginuid : '';
    console.log("分享id" + inviteuid);
    if (util.orgid == '15671'){
      return {
        title: that.data.tc == 1 ?'打造全方位的招聘服務':'打造全方位的招聘服务',
        path: '/pages/index/index?&inviteuid=' + inviteuid
        };
    } else if (util.orgid == '18535') {
      return {
        title: that.data.tc == 1 ? '新天地進駐家家公寓，找房找我！' : '新天地进驻家家公寓，找房找我！',
        path: '/pages/hotel-index/hotel-index?&inviteuid=' + inviteuid
      };
    } else{
      return {
        title: that.data.org_name,
        path: '/pages/index/index?&inviteuid=' + inviteuid
      };
    }
  },


  showEWM: function (e) {
    var shareImgUrl = e.currentTarget.dataset.imgsrc;
    console.log("图片链接：" + shareImgUrl);
    wx.previewImage({
      current: shareImgUrl,
      urls: [shareImgUrl]
    })
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },
  goAtherPageRedirect: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.redirectTo({ url: url })
  },

  //保存formId
  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
  },
  
  makeCallPhone: function (e) {
    var phoneNum = e.currentTarget.dataset.number;
    console.log("phoneNum:" + phoneNum);
    wx.makePhoneCall({
      phoneNumber: phoneNum,
      success: function (e) {
        console.log("make call success:", JSON.stringify(e));
      },
      fail: function (e) {
        console.log("make call fail:", JSON.stringify(e));
      }
    })
  },
  goMapView: function (e) {
    var addr = e.currentTarget.dataset.addr;
    var lat = parseFloat(addr.lat);
    var lon = parseFloat(addr.lon);
    wx.openLocation({
      latitude: lat,
      longitude: lon,
      scale: 20,
      name: addr.name,
      address: addr.address
    })
  },

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },
  showRoomTypes: function () {
    this.setData({
      showRoomTypes: this.data.showRoomTypes == true ? false : true
    })
  },
  // 读取主题
  loadAttributeGroups: function () {
    var that = this;
    var params = {
      publickey: util.publiccode,
      ac: "getAttributeGroups",
      orgid: util.orgid,
    }
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("主题数据18535：", result);
        for (var i = 0; i < result.length; i++) {
          if (result[i].groupName == that.data.searchVal) {
            result[i].checked = true;
          } else {
            result[i].checked = false;
          }
        }
        that.setData({
          attrList: result
        });
      }
    });
  },

  getGoodsClassly: function () {
    //读取商品分类数据
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "goodstype",
        "tc": that.data.tc
      },
      success: function (responseData) {
        console.log("商品分类数据：", responseData.data);
        var goodsType = responseData.data;
        if (goodsType.msg) {
          wx.hideLoading();
        } else {
          that.setData({
            goodsTypeArray: goodsType
          })
          for (var i = 0; i < goodsType.length; i++) {
            that.loadFenleiGoodsData(goodsType[i], i);
          }
        }
      }
    });
  },
  loadFenleiGoodsData: function (goodsTypeOb, index) {
    var that = this;
    var goodsId = goodsTypeOb.goods_id;
    var params = {
      publickey: util.publiccode,
      ac: "topiclist",
      topictype: '4',
      toporder: '1',
      tc: that.data.tc,
      orgid: util.orgid,
      gtype: goodsId,
      // zhiding: '1',
      page: 1,
      num: 10
    };
    console.log("商品参数：", params);
    util.api({
      data: params,
      success: function (responseData) {
        var result = responseData.data;
        console.log("商品数据" + goodsId + ": ", result);
        if (result.msg) {
        } else {
          var count = result.length;
          // 最低价
          var pricestart = 1000000000;
          result.forEach(function (m, i) {
            result[i].count = count;
            let pp = parseInt(m.sellprice)

            if ( pp < pricestart){
              pricestart = pp
            }
            // that.getKucunToday(result[i].id)
          });

          that.data.ghsData.forEach(function (m, i) {
            if (m.gcataid == goodsId) {
              m.pricestart = pricestart / 100;
              m.goodsArray = result
            }
          });
        }
        that.setData({
          ghsData: that.data.ghsData
        })
        console.log("ghsData商品数据", that.data.ghsData);
        wx.hideLoading();
      }
    });
  },  

})